<script lang="ts" setup>
import { ElUpload, ElIcon, ElMessage } from 'element-plus';
import { ref } from 'vue';
import { putFile } from '#/api/system/oss';

interface Props {
  imgUrl?: string;
  disabled?: boolean;
  acceptImg?: string;
  isShowTip?: object;
}

const props = withDefaults(defineProps<Props>(), {
  imgUrl: '',
  disabled: false,
  acceptImg: '',
  isShowTip: {
    isShow: false,
    message: '',
  },
});
const emit = defineEmits(['updateImg']);
const logoFile = ref<UploadFile | null>(null);

const handleUploadChange = (uploadFile: UploadFile) => {
  if (uploadFile.status === 'ready') {
    logoFile.value = uploadFile;
    uploadLogoToServer();
  }
};

const handleLogoUpload = (file: File) => {
  const validTypes = ['image/jpeg', 'image/png'];
  if (!validTypes.includes(file.type)) {
    ElMessage.error('请上传JPG/PNG格式');
    return false;
  }

  if (file.size > 5 * 1024 * 1024) {
    ElMessage.error('文件大小超过5MB');
    return false;
  }
  return true;
};

const uploadLogoToServer = async () => {
  if (!logoFile.value?.raw) return;

  const formData = {
    file: logoFile.value.raw,
    path: logoFile.value.raw.name,
  };

  try {
    const { data } = await putFile(formData);
    emit('updateImg', data.url);
    logoFile.value = null;
  } catch (err) {
    ElMessage.error('上传失败');
  }
};
</script>
<template>
  <div>
    <ElUpload
      action=""
      :auto-upload="false"
      :show-file-list="false"
      :accept="props.acceptImg"
      :before-upload="handleLogoUpload"
      @change="handleUploadChange"
      class="logo-uploader"
      list-type="picture-card"
      :disabled="props.disabled"
    >
      <div v-if="props.imgUrl" class="logo-preview">
        <img :src="props.imgUrl" alt="系统LOGO" class="logo-image" />
      </div>
      <ElIcon v-else><Plus /></ElIcon>
      <template #tip v-if="props.isShowTip.isShow">
        <div class="el-upload__tip">{{ props.isShowTip.message }}</div>
      </template>
    </ElUpload>
  </div>
</template>
<style scoped>
.logo-image {
  width: 148px;
  height: 148px;
  object-fit: contain;
}
</style>
